// src/plugins/axios.ts
import axios from 'axios';
import { API_BASE_URL } from '@/config.ts';
import { ElMessage } from 'element-plus';

const axiosInstance = axios.create({
    baseURL: API_BASE_URL,
});

// 请求拦截器：可以在这里添加 Token 或其他请求头
axiosInstance.interceptors.request.use((config) => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers['token'] = `${token}`;
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

export const getCommon = async (url: string) => {
    try {
        const token = localStorage.getItem('token');
        const response = await axios.get(`${API_BASE_URL}${url}`, {
            headers: { token: token },
        });

        // 如果后端返回的 code 为 1，弹框提示
        if (response.data.code === 1) {
            ElMessage.error('请先登录才能继续操作');
        }

        return response.data;
    } catch (error) {
        console.error('请求出错:', error);
        ElMessage.error('请求失败，请重试');
        throw error;
    }
};

export default axiosInstance;
